﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.IServer.Management_Arena;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Field
{
    [Route("api/[controller]")]
    [Function("场地管理", null, "site", "../views/Home/site/index.vue")]
    [ApiController]
    [Authorize]
    public class FieldsController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IFieldTypesServer _typeServer;
        private readonly IFieldsServer _fieldsServer;
        private readonly IVenuesServer _venuesServer;
        public FieldsController(IMapper mapper, IFieldTypesServer typeServer, IFieldsServer fieldsServer, IVenuesServer venuesServer)
        {
            _mapper = mapper;
            _typeServer = typeServer;
            _fieldsServer = fieldsServer;
            _venuesServer = venuesServer;
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <param name="typeid"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}/{typeid}")]
        [Function("场地详情", null, "site", "../views/Home/site/siteInfo/index.vue")]
        public async Task<JsonResult> GetFieldesPage(int pageIndex = 1, int pageSize = 10, int typeid = 0, string searchaString = " ")
        {
            var result = new ApiResult<PageModel<FieldDto>>() { Success = false, Message = "操作失败" };

            string? venueIdClaim = User.FindFirst("VenueId")?.Value;

            Guid.TryParse(venueIdClaim, out Guid venueId);

            //Fields场地表,VenueApplications球馆表,FieldTypes 场地类型
            Expressionable<Fields, Venues, FieldTypes> expressionable = new Expressionable<Fields, Venues, FieldTypes>();


            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b, c) => b.VenueName.Contains(searchaString) || a.FieldName.Contains(searchaString));

            expressionable.AndIF(typeid != 0, (a, b, c) => c.FieldTypeID == typeid);

            //如果是球馆管理员登录就要查询当前球馆的场地
            expressionable.AndIF(venueId != default, (a, b, c) => a.VenueID == venueId);

            var data = await _fieldsServer.FieldsQuery(expressionable.ToExpression(), pageIndex, pageSize);

            result.Data = _mapper.Map<PageModel<FieldDto>>(data);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取球馆预约不同时间段的价格和场地预约信息
        /// </summary>
        /// <param name="tId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("SessionPrice/{pageIndex:int}/{pageSize:int}/{tId:int}/{display}")]
        [Route("SessionPrice/{pageIndex:int}/{pageSize:int}/{tId:int}/{order:int}/{display}")]
        public async Task<JsonResult> GetSessionPrice(int tId, string display, int pageIndex = 1, int pageSize = 10,int order=0)
        {
            var result = new ApiResult<PageModel<VenuePricingDTO>>() { Success = false, Message = "操作失败" };

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            if (venueIdClaim == null || !Guid.TryParse(venueIdClaim, out Guid venueId))
            {
                result.Message = "对当前场地没有操作权限";
                return new JsonResult(result);
            }

            //如果没传递必要的参数直接返回
            if (venueIdClaim == default || tId == 0) return new JsonResult(result);

            if (!display.IsValidIsoDate())
            {
                display = DateTime.Today.ToString("yyyy-MM-dd");
            }

            Expressionable<Venues, Fields> expressionable
                = new Expressionable<Venues, Fields>();

            expressionable.And((a, b) => a.VenueID.Equals(venueIdClaim) && b.FieldTypeID == tId);

            var data = await _fieldsServer.SessionPriceQuery(expressionable.ToExpression(), pageIndex, pageSize, display, order);

            result.Data = data;

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }



        /// <summary>
        /// 添加单个场地
        /// </summary>
        [HttpPost("create")]
        public async Task<JsonResult> CreateField([FromBody] FieldDto dto)
        {
            var result = new ApiResult();

            // 基础校验
            var validationResult = ValidateFieldDto(dto);
            if (!validationResult.Success)
            {
                result.Success = false;
                result.StatusCode = 400;
                result.Message = validationResult.Message;
                return new JsonResult(result);
            }

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            Guid.TryParse(venueIdClaim, out Guid vId);

            // DTO 转实体
            var field = ConvertToEntity(dto, vId);

            // 调用服务层
            var addResult = await _fieldsServer.AddAsync(field);
            if (addResult <= 0)
            {
                result.Success = false;
                result.Message = "场地创建失败";
                return new JsonResult(result);
            }
            result.Success = true;
            result.Message = "创建成功";
            return new JsonResult(result);
        }

        /// <summary>
        /// 批量添加场地
        /// </summary>
        [HttpPost("batch-create")]
        public async Task<JsonResult> BatchCreateFields([FromBody] List<FieldDto> dtos)
        {
            var result = new ApiResult();

            if (dtos == null || !dtos.Any())
            {
                result.Success = false;
                result.Message = "请求参数不能为空";
                return new JsonResult(result);
            }

            var errorList = new List<string>();
            var entities = new List<Fields>();

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            Guid.TryParse(venueIdClaim, out Guid vId);

            // 批量校验并转换
            foreach (var (dto, index) in dtos.Select((d, i) => (d, i)))
            {
                var validation = ValidateFieldDto(dto);
                if (!validation.Success)
                {
                    errorList.Add($"第 {index + 1} 条数据错误：{validation.Message}");
                    continue;
                }
                entities.Add(ConvertToEntity(dto, vId));
            }

            if (errorList.Any())
            {
                result.Success = false;
                result.Message = string.Join("；", errorList);
                return new JsonResult(result);
            }

            // 调用服务层批量插入
            var addResult = await _fieldsServer.AddAsync(entities);
            if (addResult != entities.Count)
            {
                result.Success = false;
                result.Message = $"预期插入 {entities.Count} 条，实际插入 {addResult} 条";
                return new JsonResult(result);
            }
            result.Success = true;
            result.Message = "批量创建成功";
            return new JsonResult(result);
        }

        /// <summary>
        /// 修改场地信息
        /// </summary>
        [HttpPut("update")]
        public async Task<JsonResult> UpdateField([FromBody] FieldDto dto)
        {
            var result = new ApiResult();

            // 基础校验
            if (dto.id <= 0)
            {
                result.Success = false;
                result.Message = "场地ID无效";
                return new JsonResult(result);
            }

            var validationResult = ValidateFieldDto(dto);
            if (!validationResult.Success)
            {
                result.Success = false;
                result.Message = validationResult.Message;
                return new JsonResult(result);
            }

            // 检查场地是否存在
            var existing = await _fieldsServer.QueryAsync(dto.id);
            if (existing == null || existing.IsDeleted == true)
            {
                result.Success = false;
                result.Message = "指定场地不存在";
                return new JsonResult(result);
            }

            // 更新实体
            var field = ConvertToEntity(dto);
            field.FieldID = dto.id; // 确保ID正确
            field.CreatedAt = existing.CreatedAt; // 保留原始创建时间
            field.UpdatedAt = DateTime.Now;

            var updateResult = await _fieldsServer.UpdateAsync(field);
            if (!updateResult)
            {
                result.Success = false;
                result.Message = "场地更新失败";
                return new JsonResult(result);
            }

            result.Success = true;
            result.Message = "更新成功";
            return new JsonResult(result);
        }

        #region 私有方法
        /// <summary>
        /// 返回一个元组
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private (bool Success, string Message) ValidateFieldDto(FieldDto dto)
        {
            if (dto == null) return (false, "DTO不能为空");

            if (string.IsNullOrWhiteSpace(dto.FieldName))
                return (false, "场地名称不能为空");

            if (dto.TId <= 0)
                return (false, "场地类型ID必须大于0");

            if (!new short?[] { 1, 3 }.Contains(dto.Status))
                return (false, "运营状态值无效（有效值：1-维护中，3-可预订）");

            return (true, null);
        }
        /// <summary>
        /// 实体类型转换
        /// 为什么不使用map因为我要根据当前管理员 对VId进行动态赋值
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        private Fields ConvertToEntity(FieldDto dto, Guid guid = default)
        {
            return new Fields
            {
                VenueID = dto.VId == default ? guid : dto.VId,
                FieldTypeID = dto.TId,
                FieldName = dto.FieldName.Trim(),
                Status = dto.Status,
                IsDeleted = false,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
        }
        #endregion

    }
}
